package com.javaking.clanteam.hvz;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.javaking.clanteam.hvz.sql.HVZUser;
import com.javaking.clanteam.hvz.sql.SQLRelay;
import com.javaking.clanteam.hvz.utils.BarcodeScanActivity;

/**
 * The Class EditUserActivity.
 */
public class EditUserActivity extends Activity {
	
	/** The Constant SCAN_BARCODE for intent request codes. */
	private static final int SCAN_BARCODE = 0;
	
	/** The Constant SCAN_KILLCODE for intent request codes. */
	private static final int SCAN_KILLCODE = 1;
	
	/** The user that we will be editing. */
	private HVZUser user;
	
	/** The killcode scanned by the scanner intent. */
	private String killcode;
	
	/** What opperation are we performing on the user. */
	private int mode;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// Basic init for onCreate
		super.onCreate(savedInstanceState);
		setContentView(R.layout.edit_user);
		
		// get the extras that were set when this intent was called.
		Bundle extras = getIntent().getExtras();
		try {
			// setup the user object based off the string extra.
			user = new HVZUser(extras.getString("HVZUser_string"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		// Build a string containing all the user info that a 
		// user might want.
		StringBuilder sb = new StringBuilder();
		sb.append("ID:"+user.getId()+'\n');
		sb.append("Barcode:"+user.getBarcode()+'\n');
		sb.append("Username:"+user.getUsername()+'\n');
		sb.append("Usertype:"+user.getUsertype()+'\n');
		sb.append("Status:"+user.getStatus()+'\n');
		
		// Set the string we just created to the userInfo text view.
		((TextView)findViewById(R.id.userInfo)).setText(sb.toString());
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Get the extras for the return intent.
		Bundle extras = data.getExtras();
		
		// Extract the barcode from those extras
		String scanResult = extras.getString("barcode");
		
		// Switch based off what we asked the returning activity to do.
		switch(requestCode)
		{
		case SCAN_BARCODE: // We wanted to scan a user barcode
			// set the user's barcode
			user.setBarcode(scanResult);
			break;
		case SCAN_KILLCODE: // We wanted to scan a killcode
			// set the global 'killcode'
			killcode = scanResult;
			break;
		default:
			break;
		}
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.edit_user_menu, menu);
	    return true;
	}
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Get the item id and store it to the global 'mode' variable
		mode = item.getItemId();
		
		// We need to do different things based off which item was clicked.
		switch(mode)
		{
		case R.id.remove_user: // remove the user that is stored in the 'user' object
			// Call our SQL remove function and store the result
			finishWithResult(SQLRelay.removeUser(user));
			return true;
		case R.id.modify_user:
			setContentView(R.layout.modify_user); // Just show the modify user layout
			return true;
		case R.id.kill_user:
			finishWithResult(SQLRelay.kill(user)); // Call SQL and finish with the result
			return true;
		case R.id.resurrect_user: 
			finishWithResult(SQLRelay.resurrect(user)); // Call SQL and finish with the result
			return true;
		case R.id.assign_killcode:
			// Show the 'scan killcode' dialog.
			setContentView(R.layout.killcode_actions);
			((TextView)findViewById(R.id.killcode_label))
				.setText("Scan the killcode you are assigning:");
			return true;
		case R.id.score_killcode:
			// Show the 'scan killcode' dialog.
			setContentView(R.layout.killcode_actions);
			((TextView)findViewById(R.id.killcode_label))
				.setText("Scan the killcode you are scoring:");
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * 
	 * @param result A JSONObject containing the result of a our SQL query.
	 */
	private void finishWithResult(JSONObject result) {
		Intent resultIntent = new Intent(); // define an intent to tell our caller the result
		try {
			
			// The result should be formatted like {SUCCESS or ERROR=stuff}
			// so we're getting the key (SUCCESS or ERROR) and then 
			// getting the value from that key and storing it to the result.
			String key = result.names().getString(0);
			resultIntent.putExtra(key,
					result.getString(key));
		} catch (JSONException e) {
			// An error occurred so we'll report it how the caller expects it.
			resultIntent.putExtra("ERROR", "An unknown error occurred");
		}
		setResult(RESULT_OK, resultIntent); // set this activity's result
		finish(); // quit
	}
	
	/**
	 * This is a function that gets called when the user clicks the
	 * scan button. It will call an intent with the appropriate requestCode
	 */
	public void scanBarcode(View v)
	{
		// Setup the scanIntent
		Intent scanIntent = new Intent(this, BarcodeScanActivity.class);
		
		// Set the request code based off which can mode we're in.
		int requestCode;
		switch(mode)
		{
		case R.id.modify_user:
			requestCode = SCAN_BARCODE;
			break;
		case R.id.assign_killcode: case R.id.score_killcode:
			requestCode = SCAN_KILLCODE;
			break;
		default:
			requestCode = 0;
		}
		
		
		startActivityForResult(scanIntent, requestCode); // start the activity
	}
	
	/**
	 * Called when the use clicks on the button to perform an action.
	 * Will decide what to do based off what mode was set earlier.
	 */
	public void performAction(View v)
	{
		switch(mode)
		{			
		case R.id.modify_user:
			EditText usernameEdit = (EditText)findViewById(R.id.newUsername);
			String newUsername = usernameEdit.getText().toString();
			user.setUsername(newUsername);
			SQLRelay.removeUser(user);
			finish();
			break;
		case R.id.assign_killcode:
			JSONObject result = SQLRelay.assign_killcode(user,killcode);
			Intent resultIntent = new Intent();
			try {
				resultIntent.putExtra(result.names().getString(0),
						result.getString(result.names().getString(0)));
			} catch (JSONException e) {
				resultIntent.putExtra("ERROR", "An unknown error occurred");
			}
			setResult(RESULT_OK, resultIntent);
			break;
		case R.id.score_killcode:
			result = SQLRelay.score_killcode(user,killcode);
			resultIntent = new Intent();
			try {
				resultIntent.putExtra(result.names().getString(0),
						result.getString(result.names().getString(0)));
			} catch (JSONException e) {
				resultIntent.putExtra("ERROR", "An unknown error occurred");
			}
			setResult(RESULT_OK, resultIntent);
			break;
		default:
			break;
		}
		finish();
	}

}
